/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.common.conversion;

import static org.eclipse.xtext.util.Strings.isEmpty;

import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.conversion.impl.AbstractLexerBasedConverter;
import org.eclipse.xtext.nodemodel.INode;

/**
 * Converts integer numbers to {@code long}s.
 * 
 * @author Thomas Kistel
 * @version $Revision: 758 $
 */
public class LongValueConverter extends AbstractLexerBasedConverter<Long> {

    /**
     * Creates an {@code int} from the given input, if the given input represents an integer number.
     * 
     * @param string the given input.
     * @param node the parsed node including hidden parts.
     * @return the new {@code int}.
     * @throws ValueConverterException if the given input is {@code null}, empty or does not represent an
     *         integer number.
     */
    public Long toValue(String string, INode node) throws ValueConverterException {
        if (isEmpty(string))
            throw new ValueConverterException("Couldn't convert empty string to long.", node, null);
        try {
            return Long.parseLong(string, 10);
        } catch (NumberFormatException e) {
            throw parsingError(string, node, e);
        }
    }

    private ValueConverterException parsingError(String string, INode node, Exception cause) {
        return new ValueConverterException("Couldn't convert '" + string + "' to long.", node, cause);
    }
}
